<template>
  <!-- 表格 end  弹框-->
  <a-modal
    :title="title"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :openType="openType"
    :phaseListInfo="phaseListInfo"
    @cancel="clickCancel()"
    @ok="clickConfirm()"
    width="650px"
    okText="保存"
  >
    <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item label="项目编号" prop="no">
        <a-input v-model="form.no" placeholder="请输入临床研究方案编号" :disabled="stateInput" />
      </a-form-model-item>
      <a-form-model-item label="Protocol号" prop="protocolNo">
        <a-input v-model="form.protocolNo" placeholder="请输入临床研究注册获批编号" />
      </a-form-model-item>
      <a-form-model-item label="项目全名" prop="name">
        <a-input v-model="form.name" placeholder="请输入项目全名" />
      </a-form-model-item>
      <a-form-model-item label="申办方" prop="sponsorIds">
        <a-select
          style="width: 333px;"
          v-model="form.sponsorIds"
          mode="multiple"
          placeholder="请选择申办方"
          @change="handleChange"
        >
          <a-select-option v-for="list in phaseListInfo" :key="list.id">
            {{ list.orgName }}
          </a-select-option>
        </a-select>
        <a style="margin-left: 15px;" @click="addBidders">新增申办方</a>
      </a-form-model-item>
      <a-form-model-item label="项目状态" prop="status">
        <a-radio-group v-model="form.status">
          <a-radio :value="1"> 未启动 </a-radio>
          <a-radio :value="2"> 进行中 </a-radio>
          <a-radio :value="3"> 已关闭 </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="研究分期" prop="stage">
        <a-select v-model="form.stage" placeholder="请选择研究分期" :disabled="stateInput">
          <a-select-option v-for="item in $const.SPONSOR_STAGE" :key="item.value" :value="item.value">
            {{ item.desc }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <div style="color: red; text-align: center; margin-bottom: 20px" v-if="stateInput && !bothStateInput">请完善项目信息</div>
      <!-- <a-form-model-item label="项目预算" prop="budget" v-if="isEditProject ? (this.$store.getters.userInfo.isAdmin ? true : false) : true">
        <a-input
          :max="99999999.99"
          v-model="form.budget"
          style="width:451px"
          placeholder="请输入项目预算"
          :precision="2"
          @input="(e) => (this.form.budget = $commonMethods.moneyCheck(e.target.value))"
          :disabled="stateInput && bothStateInput" />
      </a-form-model-item> -->
      <a-form-model-item label="合同编号" prop="contractNo" v-if="isEditProject ? (this.$store.getters.userInfo.isAdmin ? true : false) : true">
        <a-input v-model="form.contractNo" placeholder="请输入合同编号" :disabled="stateInput && bothStateInput" />
      </a-form-model-item>
      <!-- <a-form-model-item label="立项时间" prop="buildTime">
        <a-date-picker
          v-model="form.buildTime"
          placeholder="请输入立项时间"
          v-decorator="['range-time-picker']"
          show-time
          valueFormat="YYYY-MM-DD HH:mm:ss"
          @change="windowIndateChange"
        />
      </a-form-model-item> -->
      <!-- isAdmin为1则可修改业务，否则禁止修改 -->
      <!-- 新增项目显示业务人员 编辑时根据是否为admin来决定显示与否 -->
      <!-- v-if="isEditProject ? (this.$store.getters.userInfo.isAdmin ? true : false) : true" -->
      <a-form-model-item label="业务人员" prop="createrId" v-if="isEditProject ? (this.$store.getters.userInfo.isAdmin ? true : false) : false">
        <a-select v-model="form.createrId" placeholder="请选择业务人员" allowClear>
          <a-select-option v-for="item in business" :key="item.key" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- <a-form-model-item label="研究分期" prop="pic">
          <a-input-number
            :style="{ width: '200px' }"
            v-model="form.pic"
            :default-value="1000"
            :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            @change="onChange"
          />
        </a-form-model-item> -->
    </a-form-model>
    <AddSponsorModal
      :visible="showModal"
      @modalOk="addSubmit"
      @modalCancel="addCancel"
      :type="currentType"
      :openType="sponsorOpenType"
      :editContent="modify"
      :business="sponsorBusiness"
    />

  </a-modal>
</template>
<script>
import monitor from '@/utils/monitor'
import addModal from '@/monitor/views/overview/allItems/addModal.js'
import AddSponsorModal from './components/AddSponsorModal.vue'
// import AddSponsorModal from '@views/organization/components/AddModal.vue'
import { getDictionary, getInstitutionsAdd } from '@/api/organization/organization'

import { getAdminList } from '@/api/common'
import moment from 'moment'
import clonedeep from 'lodash.clonedeep'

const watch = monitor(addModal)

export default {
  props: {
    isEditProject: {
      default: false,
      type: Boolean
    },
    visible: {
      default: false,
      type: Boolean
    },
    phaseListInfo: {
      type: Array,
      default: () => []
    },
    editContent: {
      type: Object,
      default: () => {}
    },
    openType: {
      type: Number,
      default: 0
    }
  },
  components: {
    AddSponsorModal
  },
  data () {
    return {
      that: this,
      windowIndate: '',
      startTime: '',
      confirmLoading: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      title: '项目', // 动态标题
      stateInput: false, // 动态输入框状态
      bothStateInput: false,
      form: {
        status: 1
      },
      business: [],
      rules: {
        // 校验规则
        protocolNo: [{ required: false, message: '请输入protocol号', trigger: 'change' }],
        name: [
          { required: true, message: '请输入项目名称', trigger: 'change' },
          { max: 80, message: '项目名称不得超过80个字符' }
        ],
        sponsorIds: [{ required: true, message: '请选择申办方', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        stage: [{ required: true, message: '请选择分期', trigger: 'change' }],
        // budget: [
        // { required: true, message: '请输入项目预算', trigger: 'change' },
        // { pattern: /^\d{1,8}(\.\d{0,2}$)?/, message: '数字不能超过10位，小数点后不能超过两位' }
        // ],
        no: [{ required: true, message: '请输入项目编号.', trigger: 'change' }],
        contractNo: [{ required: true, message: '请输入合同编号', trigger: 'change' }],
        // buildTime: [{ required: true, message: '请输入立项时间', trigger: 'change' }],
        createrId: [{ required: false, message: '请输入立项时间', trigger: 'change' }]
      },
      modify: {},
      sponsorOpenType: 0,
      showModal: false,
      currentType: 1,
      sponsorBusiness: []
    }
  },
  created () {
    this.getAdminList()
    this.getBodyType()
  },
  watch: {
    phaseListInfo (listInfo) {
      this.phaseListInfo = listInfo
    },
    visible (newv) {
      if (newv === true) {
        this.form = this.openType === 0 ? { status: 1 } : clonedeep(this.editContent)
        // this.form.budget = null
        // this.form.contractNo = null
        const businessIds = this.business.map(item => item.id)
        if (businessIds.indexOf(this.editContent.createrId) < 0) this.form.createrId = this.editContent.businessName
      }
      if (this.openType === 0) {
        this.stateInput = false
        this.bothStateInput = false
        this.title = '新增项目'
      } else if (this.openType === 1 && this.editContent.status === 2) {
        this.stateInput = true
        // !Number(this.form.budget) ||
        if (!this.form.contractNo) {
          this.bothStateInput = false
        } else {
          this.bothStateInput = true
        }
        this.title = '编辑项目'
        // this.judgeRole = this.$store.getters.userInfo.isAdmin ? '' : true
      } else {
        this.stateInput = false
        this.bothStateInput = false
      }
    }
  },
  methods: watch({
    // 获取机构列表传给新建申办方组件
    getBodyType () {
      getDictionary({
        typeCode: 10001011
      }).then(res => {
        this.sponsorBusiness = res
      })
    },
    addBidders () {
      this.addSponsors()
      // this.$router.push({
      //   name: 'organization'
      // })
      this.modify = {}
      this.showModal = true
    },
    moment, // moment 用来把日期或时间字符串转换成moment类型
    windowIndateChange (date, dateString) {
      this.windowIndate = dateString
    },
    handleChange (value) {
      console.log(`${value}`)
      this.selectSponsors()
    },
    // 获取业务人员下拉列表
    getAdminList () {
      getAdminList()
        .then(res => {
          this.business = res
        })
        .catch(() => {})
    },
    clickConfirm () {
      // this.form.sponsorIds = JSON.stringify(this.form.sponsorIds)
      // this.form.sponsorIds = this.form.sponsorIds.toString()
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const businessIds = this.business.map(item => item.id)
          if (businessIds.indexOf(this.form.createrId) < 0) this.form.createrId = this.editContent.createrId
          // this.form.sponsorIds = this.form.sponsorIds.toString()
          const commitData = JSON.parse(JSON.stringify(this.form))
          commitData.sponsorIds = commitData.sponsorIds.toString()
          this.$emit('modalOk', commitData)
          // this.$emit('modalOk', this.form)
          this.addProject()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clickCancel () {
      this.$emit('modalCancel')
      setTimeout(() => {
        this.$refs.ruleForm.resetFields()
        this.form = this.$options.data().form
      }, 100)
    },
    // 时间选择器
    onChange (date, dateString) {
      console.log(date, dateString)
    },
    // 新增申办方
    addSubmit (e) {
      getInstitutionsAdd({ ...e, type: this.currentType })
        .then(res => {
          this.showModal = false
          this.$message.success('添加成功')
          // 让父组件再去重新请求一次接口获取最新的申办方列表
          this.$emit('getLatestSponsor')
        })
    },
    // 取消新增申办方
    addCancel () {
      this.showModal = false
    },
    // 新增项目埋点
    addProject () {},
    // 选择申办方埋点
    selectSponsors () {},
    // 添加申办方埋点
    addSponsors () {}
  })
}
</script>
